package org.dakuo.sgfyModel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

public class SgfyConstruction {

	public static final String CONSTRUCTION_LUMBER_CN = "林场";
	public static final String CONSTRUCTION_CLAY_CN = "石矿";
	public static final String CONSTRUCTION_IRON_CN = "铁矿";
	public static final String CONSTRUCTION_CROP_CN = "农田";

	private String name;
	private String nameCN;
	private int id;
	private String url;
	private int level;
	String updateURI;
	double updateDuration;

	private float[] consumeResource = { 0, 0, 0, 0, 0 };

	private boolean inWorkStatus;

	public SgfyConstruction() {
		name = "";
		nameCN = "";
		id = 0;
		url = "";
		updateURI = "";
		level = 0;
		inWorkStatus = false;
		updateDuration = -1;
	}

	public SgfyConstruction(String n, String nCn, int id, String url,
			int level, boolean inWorkStatus) {

		this.setName(n);
		this.setNameCN(nCn);
		this.setId(id);
		this.setUrl(url);
		this.setLevel(level);
		this.setInWorkStatus(inWorkStatus);
		updateDuration = -1;
	}

	public SgfyConstruction(String nCn, String level, String url) {
		this.setNameCN(nCn);
		this.setUrl(url);
		this.setLevel(Integer.parseInt(level));
		updateDuration = -1;
	}

	public SgfyConstruction(String nCn, String level) {
		this.setNameCN(nCn);
		this.setLevel(Integer.parseInt(level));
		updateDuration = -1;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getUrl() {
		return url;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public int getLevel() {
		return level;
	}

	public void setInWorkStatus(boolean inWorkStatus) {
		this.inWorkStatus = inWorkStatus;
	}

	public boolean isInWorkStatus() {
		return inWorkStatus;
	}

	public void workDone() {
		this.inWorkStatus = false;
		this.setLevel(this.getLevel() + 1);
	}

	public void setResNeed(float l, float cl, float ir, float cr, float po) {
		float f[] = { l, cl, ir, cr, po };
		this.consumeResource = f;
	}

	public float[] getResNeed() {
		return consumeResource;
	}

	public void setNameCN(String nameCN) {
		this.nameCN = nameCN;
	}

	public String getNameCN() {
		return nameCN;
	}

	public boolean getInfo(String id2, List<Cookie> cookieList, String hostURI) {
		try {
			DefaultHttpClient httpClient = new DefaultHttpClient();

			Iterator<Cookie> ci = cookieList.iterator();
			while (ci.hasNext())
				httpClient.getCookieStore().addCookie(ci.next());

			/**
			 * Get resDetail info
			 */
			String resDetail = hostURI + "index.php?act=" + this.url
					+ "&villageid=" + id2 + "&rand=" + "775836";
			HttpGet httpGet = new HttpGet(resDetail);
			httpGet
					.setHeader(
							"User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)");
			httpGet
					.addHeader("Accept",
							"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			httpGet.addHeader("Accept-Language", "en-us,en;q=0.5");
			httpGet.addHeader("Accept-Charset",
					"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			httpGet.addHeader("Content-Type",
					"application/x-www-form-urlencoded");

			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(entity.getContent()));
				try {

					Pattern pUpdate = Pattern
							.compile(
									".*(MM_xmlLoad\\(')(\\w+\\.\\w+\\&\\w+=\\d+)(.*开始升级</a>$)",
									Pattern.DOTALL);
					Pattern pUpdateDuration = Pattern.compile(
							"sgtitle=\"所需时间\"\\s*/>\\s*(\\d+):(\\d+):(\\d+).*</p>$",
							Pattern.DOTALL);
					Matcher m;
					Matcher mUpdateDuration;
					String line = reader.readLine();
					while (line != null) {
						m = pUpdate.matcher(line);
						mUpdateDuration = pUpdateDuration.matcher(line);
						if (m.find()) {
							this.updateURI = m.group(2);
						}else if(mUpdateDuration.find()){
							int hour = Integer.parseInt(mUpdateDuration.group(1));
							int min = Integer.parseInt(mUpdateDuration.group(2));
							int second = Integer.parseInt(mUpdateDuration.group(3));
							this.updateDuration = hour*3600*1000+min*60*1000+second*1000;
						}
						else {
							// System.out.println(line);
						}
						line = reader.readLine();
					}

				} catch (IOException ex) {

					throw ex;

				} catch (RuntimeException ex) {

					httpGet.abort();
					throw ex;

				} finally {

					reader.close();

				}
			}
			cookieList = httpClient.getCookieStore().getCookies();

			httpClient.getConnectionManager().shutdown();
			return true;

		} catch (Exception e) {

			System.out.println(e.getStackTrace());
			return false;
		}
	}
			/**
			 * update resource
			 */
		public boolean update(String id2, List<Cookie> cookieList, String hostURI) {
			try {
			String updateU = hostURI + "index.php?act=" + updateURI
					+ "&villageid=" + id2 + "&rand=" + "775836";
			
			DefaultHttpClient httpClient = new DefaultHttpClient();

			Iterator<Cookie> ci = cookieList.iterator();
			while (ci.hasNext())
				httpClient.getCookieStore().addCookie(ci.next());

			HttpGet httpGet = new HttpGet(updateU);
			httpGet
					.setHeader(
							"User-Agent",
							"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)");
			httpGet
					.addHeader("Accept",
							"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			httpGet.addHeader("Accept-Language", "en-us,en;q=0.5");
			httpGet.addHeader("Accept-Charset",
					"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			httpGet.addHeader("Content-Type",
					"application/x-www-form-urlencoded");

			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			
			if (entity != null) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(entity.getContent()));
				try {
					String line = reader.readLine();
					while (line != null) {
//						System.out.println(line);
						line = reader.readLine();
					}

				} catch (IOException ex) {

					// In case of an IOException the connection will be released
					// back to the connection manager automatically
					throw ex;

				} catch (RuntimeException ex) {

					// In case of an unexpected exception you may want to abort
					// the HTTP request in order to shut down the underlying
					// connection and release it back to the connection manager.
					httpGet.abort();
					throw ex;

				} finally {

					// Closing the input stream will trigger connection release
					reader.close();

				}
			}

			cookieList = httpClient.getCookieStore().getCookies();

			httpClient.getConnectionManager().shutdown();
			return true;

		} catch (Exception e) {

			System.out.println(e.getStackTrace());
			return false;
		}

	}

	public boolean equals(Object obj) {
		SgfyConstruction con = (SgfyConstruction) obj;
		if (con.getNameCN().equals(this.getNameCN())
				&& con.getLevel() == this.getLevel()) {
			return true;
		}
		return false;
	}

	public String toString() {
		return nameCN + "Lv." + level + "_URI:" + url + "\n";
	}

}
